<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Sku as SkuService;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderMaterial as OrderMaterialService;

/**
 * 车间进度
 * @author King
 *
 */
class Workshop extends Admin
{

	public function initialize() {
		parent::initialize();
	}

	public function index()
	{
		$factoryKV = getFactoryKV(false);
		$factoryOutgoKV = getFactoryOutgoKV(null);
		$systemUserKV = getSystemUserKV(null);
		$groupKV = getGroupKV(0);
		if ($this->request->isAjax()) {
			$where      = $data = [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$factorId      = $this->request->param('factory_id/d', 0);
			$orderStatus    = $this->request->param('order_status/s');
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$sku    = $this->request->param('sku/s');
			$createDateRange    = $this->request->param('create_date_range/s');
			$overDateRange    = $this->request->param('over_date_range/s');
			$caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s');

			$where[] = ['status', 'in', [0,1,2]];
			$where[] = ['caichuang_status', '=', 1];
			$where[] = ['outgo_status', '=', 0];
            //订单加一级
            order_level($where,'');
			if ($factorId) {
				$where[] = ['factory_id', '=', $factorId];
			}

			if ($orderStatus != '') {
				switch ($orderStatus){
					case 1:
						$where[] = ['caigou_status', '=', 0];
						break;
					case 2:
						$where[] = ['caigou_status', '=', 1];
						$where[] = ['caichuang_status', '=', 0];
						break;
					case 3:
						$where[] = ['caichuang_status', '=', 1];
						$where[] = ['chejian_status', '=', 0];
						break;
					case 4:
						$where[] = ['chejian_status', '=', 1];
						$where[] = ['tail_status', '=', 0];
						break;
					case 5:
						$where[] = ['tail_status', '=', 1];
						$where[] = ['status', '=', 0];
						break;
					case 6:
						$where[] = ['status', '=', 2];
						break;
				}
			}
			if ($clientOrdernum != '') {
				$where[] = ['client_ordernum', '=', $clientOrdernum];
			}
			if ($sku != '') {
				$where[] = ['sku', 'like', "%".$sku."%"];
			}
			if ($createDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
				$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($overDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
				$where[] = ['over_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($caichuangOverDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
				$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
			}

			$order = "FIELD(status,2,99) ASC,chejian_status ASC,shipment_time ASC,create_time ASC";
			$data['data'] = db('order')->where($where)->page($page)->limit($limit)->orderRaw($order)->select();

			$skuService = new SkuService();
			$orderSizeService = new OrderSizeService();
			$orderMaterialService = new OrderMaterialService();
			foreach ($data['data'] as $k => $v) {
				$osList = $orderSizeService->getListByOrderId($v['id'], 'mid,order_count,daohuo_count,shicai_count,jiaohuo_tail_count,jiaohuo_count,size_name,sew_cut_count');
				$data['data'][$k]['osList'] = $osList;
				$data['data'][$k]['osJson'] = json_encode($osList);
				$data['data'][$k]['groupKV'] = [0 => '请选择'] + getGroupKV($v['factory_id']);
				$data['data'][$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
				$data['data'][$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
				$data['data'][$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
				$data['data'][$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
				$data['data'][$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
				$data['data'][$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
				$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$data['data'][$k]['group_name'] = arrayGet($groupKV, $v['group_id'], '');
				$data['data'][$k]['factory_outgo_name'] = arrayGet($factoryOutgoKV, $v['factory_outgo_id'], '');
				$data['data'][$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
				$data['data'][$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');
				//$data['data'][$k]['omList'] = $orderMaterialService->getListByOrderId($v['id']);
			}
			$data['count'] = db('order')->where($where)->count('id');
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [
			'factoryKV' => [0 => '请选择'] + $factoryKV,
			'groupKV' => $groupKV,
			'factoryOutgoKV' => $factoryOutgoKV,
		];
		return $this->assign($assign)->fetch();
	}

	/**
	 * 设置预计 完成时间
	 *
	 * @author KING
	 * @date 2014-5-23
	 *
	 */
	public function setOverTime() {
		$orderId = $this->request->param('order_id/d', 0);
		$date = $this->request->param('date');

		$data['chejian_plan_over_time'] = strtotime($date . " 00:00:00");
		$data['update_time'] = time();
		$res = db('order')->where('id', $orderId)->update($data);

		$this->addOrderLog($orderId, '', "设置车间预计完成时间为{$date}");
		if ($res) {
			return $this->Json(1);
		} else return $this->Json(0);
	}

	/**
	 * 车间完成/车间补裁片
	 */
	public function done() {
		$orderId = $this->request->param('order_id');
		$numberArr = $this->request->param('number/a', []);
        $actiontype=$this->request->param('actiontype', '');
		try {
			db()->startTrans();
            if($actiontype=='swe_cut_make_up'){ //车间补裁片
                foreach ($numberArr as $k => $v) {
                    $data = array();
                    $data['sew_cut_count'] = $v ? $v : 0;
                    $res = db('order_size')->where('mid', $k)->where('order_id', $orderId)->update($data);
                }
                $orderService = new OrderService();
                $orderInfo = $orderService->getInfoById($orderId);
                $this->addOrderLog($orderId, $orderInfo['client_ordernum'], "车间补裁片");
            }else {

                $orderService = new OrderService();
                $orderInfo = $orderService->getInfoById($orderId);
                //卡点-> 委外订单，不能在次处车间完成
                $factIdList=  db('factory')->where(['type' => 1,'status' => 1])->column('id');
                if(in_array($orderInfo['factory_id'],$factIdList)){
                    return $this->Json(0, "委外订单，不能在次处车间完成！ 请到委外管理->节点进度 做对应的操作");
                }

                $result = false;
                foreach ($numberArr as $k => $v) {
                    $data = array();
                    $data['jiaohuo_count'] = $v ? $v : 0;
                    $data['update_time'] = time();
                    $res = db('order_size')->where('mid', $k)->where('order_id', $orderId)->update($data);
                }
                // 订单的车间状态操作
                $oData = array();
                if ($orderInfo['caichuang_over_time'] == 0) {
                    $oData['caichuang_status'] = 1;
                    $oData['caichuang_over_time'] = time() - 1;
                }

                $oData['chejian_status'] = 1;
                $oData['chejian_over_time'] = time();
                db('order')->where("id", $orderId)->update($oData);

                $this->addOrderLog($orderId, $orderInfo['client_ordernum'], "车间完成");
            }
			db()->commit();
			return $this->Json(1);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	/**
	 * 回退到裁床环节
	 *
	 * @author KING
	 * @date 2020年4月27日
	 *
	 */
	public function back() {
		$orderId = $this->request->param('order_id');
		$orderService = new OrderService();
		$orderInfo = $orderService->getInfoById($orderId);
		if (!$orderInfo) {
			return $this->Json(0, '未找到该订单');
		}

		db('order_material')->where('order_id', $orderId)->update(['caichuang_status' => 0, 'caichuang_over_time' => 0]);

		// 更新order表
		$uod = ['caichuang_user_id' => 0, 'caichuang_status' => 0, 'caichuang_over_time' => 0];
		db('order')->where('id', $orderId)->update($uod);

		$this->addOrderLog($orderId, arrayGet($orderInfo, 'client_ordernum', ''), '回退到裁床环节');
		return $this->Json(1, '操作成功');
	}

    public function index_v2_ajax()
    {
        $factoryKV = getFactoryKV(false);
        $factoryOutgoKV = getFactoryOutgoKV(null);
        $systemUserKV = getSystemUserKV(null);
        $groupKV = getGroupKV(0);
        if ($this->request->isAjax()) {
            $where      = $data = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $factorId      = $this->request->param('factory_id/d', 0);
            $orderStatus    = $this->request->param('order_status/s');
            $clientOrdernum    = $this->request->param('client_ordernum/s');
            $sku    = $this->request->param('sku/s');
            $createDateRange    = $this->request->param('create_date_range/s');
            $overDateRange    = $this->request->param('over_date_range/s');
            $caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s');
            $breakType    = $this->request->param('break_type/s','');

            $where[] = ['o.status', 'in', [0,1,2]];
            $where[] = ['o.caichuang_status', '=', 1];
            $whereRaw = "o.outgo_status<=0 or ft.type=0 ";//旧的不外发的订单 或 新的不在外发工厂的订单
            //订单加一级
            order_level($where,'');
            if ($factorId) {
                $where[] = ['o.factory_id', '=', $factorId];
            }

            if ($orderStatus != '') {
                switch ($orderStatus){
                    case 1:
                        $where[] = ['o.caigou_status', '=', 0];
                        break;
                    case 2:
                        $where[] = ['o.caigou_status', '=', 1];
                        $where[] = ['o.caichuang_status', '=', 0];
                        break;
                    case 3:
                        $where[] = ['o.caichuang_status', '=', 1];
                        $where[] = ['o.chejian_status', '=', 0];
                        break;
                    case 4:
                        $where[] = ['o.chejian_status', '=', 1];
                        $where[] = ['o.tail_status', '=', 0];
                        break;
                    case 5:
                        $where[] = ['o.tail_status', '=', 1];
                        $where[] = ['o.status', '=', 0];
                        break;
                    case 6:
                        $where[] = ['o.status', '=', 2];
                        break;
                }
            }
            if ($clientOrdernum != '') {
                $where[] = ['o.client_ordernum', '=', $clientOrdernum];
            }
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', 'like', "%" . $ext_id . "%"];
                    break;
            }
            if ($sku != '') {
                $where[] = ['o.sku', 'like', "%".$sku."%"];
            }
            if ($createDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                $where[] = ['o.create_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($overDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
                $where[] = ['o.over_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($caichuangOverDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
                $where[] = ['o.caichuang_over_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($breakType != '') {
                $where[] = ['o.break_code_status', '=',$breakType];
                if($breakType !=1){
                    $where[] = ['o.tail_status', '<>', 1];
                }
            }

            $order = "FIELD(o.status,2,99) ASC,o.chejian_status ASC,o.shipment_time ASC,o.create_time ASC";
            $data['data'] = db('order o')
                ->field('o.*')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->where($where)
                ->whereRaw($whereRaw)
                ->page($page)->limit($limit)->orderRaw($order)->select();
            $skuService = new SkuService();
            $orderSizeService = new OrderSizeService();
            $orderMaterialService = new OrderMaterialService();
            foreach ($data['data'] as $k => $v) {
                $osList = $orderSizeService->getListByOrderId($v['id'], 'mid,order_count,daohuo_count,shicai_count,jiaohuo_tail_count,jiaohuo_count,size_name,sew_cut_count');
                $data['data'][$k]['osList'] = $osList;
                $data['data'][$k]['osJson'] = json_encode($osList);
                $data['data'][$k]['groupKV'] = [0 => '请选择'] + getGroupKV($v['factory_id']);
                $data['data'][$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')),'sew_cut_count'=>array_sum(array_column($osList, 'sew_cut_count')),
                    'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
                $data['data'][$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
                $data['data'][$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
                $data['data'][$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
                $data['data'][$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
                $data['data'][$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
                $data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
                $data['data'][$k]['group_name'] = arrayGet($groupKV, $v['group_id'], '');
                $data['data'][$k]['factory_outgo_name'] = arrayGet($factoryOutgoKV, $v['factory_outgo_id'], '');
                $data['data'][$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
                $data['data'][$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');
                //$data['data'][$k]['omList'] = $orderMaterialService->getListByOrderId($v['id']);
                //断码
                $data['data'][$k]['break_code']='';
                if($v['tail_status'] !=1){
                    $break_info=db('order_break')->field('size_list')->where([['client_ordernum', '=', $v['client_ordernum']],['sku','=', $v['sku']]])->find();
                    $data['data'][$k]['break_code']=isset($break_info['size_list'])?$break_info['size_list']:'';
                }
            }

            $data['count'] = db('order o')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->where($where)
                ->whereRaw($whereRaw)
                ->count('o.id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
    }
}